const { createCanvas, loadImage } = require("canvas");
const { MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT } = require("../config.json");
const textList = require("../text.json");

exports.image = (req, res) => {
  let [width, height, format, bgColor, textColor, text1] = Object.values(
    req.params
  );
  console.log(req.params);
  width = parseInt(width);
  height = parseInt(height);

  if (typeof bgColor === "undefined") {
    bgColor = "#333333";
  }
  if (typeof textColor === "undefined") {
    textColor = "#ffffff";
  }

  if (typeof text1 === "undefined") {
    text1 = getRandomArrayElements(textList, 1)[0].hitokoto;
  }

  if (isHexColor(bgColor)) {
    bgColor = `#${bgColor}`;
  }
  if (isHexColor(textColor)) {
    textColor = `#${textColor}`;
  }

  width = width > MAX_IMAGE_WIDTH ? MAX_IMAGE_WIDTH : width;
  height = height > MAX_IMAGE_HEIGHT ? MAX_IMAGE_HEIGHT : height;

  const canvas = createCanvas(width, height);
  const ctx = canvas.getContext("2d");

  // background color
  ctx.fillStyle = bgColor;
  ctx.fillRect(0, 0, width, height);

  // text
  let fontSize = width / 30;

  ctx.fillStyle = textColor;
  ctx.font = `bold ${fontSize}px 微软雅黑`;

  let text = `${width} x ${height}`;
  let textWidth = ctx.measureText(text).width;

  ctx.fillText(text, width / 2 - textWidth / 2, height - fontSize * 3);
  ctx.fillText(
    "@AlgerKong",
    width / 2 - ctx.measureText("@AlgerKong").width / 2,
    height - fontSize * 1.5
  );

  // text
  let fontSize1 = width / 16;

  ctx.fillStyle = textColor;
  ctx.font = `${fontSize1}px 微软雅黑`;
  if (text1.length > 100) {
    text1 = text1.substr(0, 100) + "...";
  }
  // 文字换行
  let textWidth1 = ctx.measureText(text1).width;
  let tWidth = width - width / 5;

  if (textWidth1 > tWidth) {
    let textArray = text1.split("");
    let tText = "";
    let tIndex = 0;
    let row = [];
    for (let i = 0; i < textArray.length; i++) {
      if (ctx.measureText(tText).width < tWidth) {
      } else {
        row.push(tText);
        tIndex = i;
        tText = "";
      }
      tText += textArray[i];
    }

    row.push(text1.substring(tIndex, text1.length));

    for (let i = 0; i < row.length; i++) {
      console.log(row[i]);
      ctx.fillText(
        row[i],
        width / 2 - tWidth / 2,
        height / 4 + fontSize1 * i + (i * fontSize1) / 2
      );
    }
  } else {
    ctx.fillText(text1, width / 2 - textWidth1 / 2, height / 2);
  }

  res.setHeader("Content-Type", `image/${format}`);
  if (format === "png") {
    canvas.pngStream().pipe(res);
  } else if (format === "jpeg" || format === "jpg") {
    canvas.jpegStream().pipe(res);
  }
};

function isHexColor(hex) {
  return (
    typeof hex === "string" && hex.length === 6 && !isNaN(Number(`0x${hex}`))
  );
}

exports.imageRandom = (req, res) => {
  let [width, height] = Object.values(req.params);
  width = parseInt(width);
  height = parseInt(height);
  width = width > MAX_IMAGE_WIDTH ? MAX_IMAGE_WIDTH : width;
  height = height > MAX_IMAGE_HEIGHT ? MAX_IMAGE_HEIGHT : height;

  const canvas = createCanvas(width, height);
  const ctx = canvas.getContext("2d");

  loadImage(`https://picsum.photos/${width}/${height}`).then((image) => {
    ctx.drawImage(image, 0, 0, width, height);

    ctx.fillStyle = "#ffffff";
    ctx.font = `bold ${width / 30}px Arial`;
    let userText = "@AlgerKong";
    let userWidth = ctx.measureText(userText).width;
    ctx.fillText(userText, width / 2 - userWidth / 2, height - width / 15);

    res.setHeader("Content-Type", "image/png");
    canvas.pngStream().pipe(res);
  });
};

// 随机返回数组中几个元素的方法
function getRandomArrayElements(arr, count) {
  var shuffled = arr.slice(0),
    i = arr.length,
    min = i - count,
    temp,
    index;
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random());
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
}
